/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package giuliani_mapelli_marocco.business;

import giuliani_mapelli_marocco.entity.Event;
import giuliani_mapelli_marocco.entity.User;
import java.util.Collection;
import java.util.Date;
import java.util.Properties;
import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


@Stateless
public class EmailManager {
    
    private final int port = 587;
    private final String host = "smtp.gmail.com";
    private final String from = "meteocalse2@gmail.com";
    private final boolean auth = true;
    private final String username = "meteocalse2@gmail.com";
    private final String password = "lavandino";
    private final String debug = "true";
    private static final String SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory";
    
    /**
     *Method that send an-email to one or more receivers using the smtp.gmail service 
     * containing a given object and message to a set of receivers
     * @param to a list of strings containing all the receivers' email-addresses
     * @param emailBody a string containing the message to be sent
     * @param object the object of the email
     * @throws MessagingException if there is a format error in one of the imput parameters
     */
    @Asynchronous
    public void sendEmail(String to, String emailBody, String object) throws MessagingException {
        
    // Setting properties of the mail session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");
    
    //setting a new authenticator 
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    };
    //creating a new mail session
    Session session = Session.getInstance(props, auth);
    session.setDebug(true);
    
    //creating a new message
    MimeMessage message = new MimeMessage(session);
    try {
        //setting recipient
        InternetAddress toAddress = new InternetAddress(to);
        message.addRecipient(Message.RecipientType.TO, toAddress);
        //setting sender, object, emailbody
        InternetAddress fromAddress = new InternetAddress(from);
        message.setFrom(fromAddress);
        message.setSubject(object);
        message.setSentDate(new Date());
        message.setText(emailBody);
       
        //send the email
        Transport.send(message);

    } catch (MessagingException ex) {
       
    }

}
    
    /**
     *send an email to a set of specified user to notify them about the invitation of an event 
     * @param event which the set of user are invited
     * @param receivers the set of user who have to receive the email
     * @throws MessagingException
     */
     @Asynchronous
    public void sendInvitationEmails(Event event, Collection<User> receivers) throws MessagingException {
          
        //creating message and object
        String object = "Invitation to the event : " + event.getName();
        String emailMessage = "Dear user, \nyou have been invited to the event " + "'" +event.getName() +"' organized by " + event.getOrganizer().getUsername() + ". \nYou can check all the details of the event by logging with your profile.\n\n The meteocal staff"; 
        
        //sending an e-mail for every recipient
        for (User u : receivers) {
        sendEmail(u.getEmail(), emailMessage, object);
        }
    }
    
    /**
     *sends an email to the receiver to notify that the weather conditions of an event he is going to attend are become bad
     * @param event the event which weather conditions are become bad
     * @param receiver who has to receive the email
     * @throws MessagingException
     */
     @Asynchronous
    public void sendDayBeforeBadWeatherEmail(Event event, User receiver) throws MessagingException {
        
        //creating message and object
        String object = "Bad weather alert for the event: " + event.getName();
        String emailMessage;
        if ( !event.getOrganizer().equals(receiver)) {
            emailMessage = "Dear user, \nwe would like to inform you that the weather for the event '" + event.getName() + "' has become bad, for further information you can check all the details of the event by logging with your profile.\n\nThe meteocal staff";
        } else {
            emailMessage = "Dear user, \nwe would like to inform you that the weather for your event '" + event.getName() + "' has become bad, for further information you can check all the details of the event by logging with your profile.\n\nThe meteocal staff";
        }
        
        
        //sending an e-mail to the recipient
        sendEmail(receiver.getEmail(), emailMessage, object);
    }
    
    /**
     *sends an email to the organizer of an event to notify three days before that the event conditions of an event has become bad. 
     * If available, also a suggested starting date is submitted in the email
     * @param event the event which weather conditions turned to be bad
     * @param receiver the organizer of the event who has to receive the email
     * @param suggestedDate the suggested date (null if no date available)
     * @throws MessagingException
     */
     @Asynchronous
    public void SendThreeDaysBadWeatherEmail(Event event, User receiver, Date suggestedDate) throws MessagingException {
        
        //creating message and object
        String object = "Bad weather alert for the event: " + event.getName();
        String emailMessage;
        if(suggestedDate!=null) {
             emailMessage = "Dear user, \nwe would like to inform you that the weather for your event '" + event.getName() + "', starting in three days,  has become bad. We suggest you to reschedule the event start on this date: " + suggestedDate + ". If you want to change the event details or to get further information you can check all the details of the event by logging with your profile.\n\nThe meteocal staff";
        } else {
             emailMessage = "Dear user, \nwe would like to inform you that the weather for your event '" + event.getName() + "', starting in three days,  has become bad. We are sorry but no good weather condition are expected in anyone of the coming days. If you want to change the event details or to get further information you can check all the details of the event by logging with your profile.\n\nThe meteocal staff";
        }
       
        
        //sending an e-mail to the recipient
        sendEmail(receiver.getEmail(), emailMessage, object);
    }
    
     /**
     *Sends email to notify an user that the modification of an event has generated time consistency problem with some events
     * @param event the event which weather conditions turned to be bad
     * @param receiver the organizer of the event who has to receive the email
     * @throws MessagingException
     */
     @Asynchronous
    public void SendTimeConsistencyAlertEmail(Event event, User receiver, String conflictingEventString) throws MessagingException {
        
        //creating message and object
        String object = "Time consistency alert for modification of event  " + event.getName();
        String emailMessage;
        
             emailMessage = "Dear user, \nwe would like to inform you that the schedule of the event  '" + event.getName() + "' has been modified. The changes made have generated time consistency problems with the following event(s): " + conflictingEventString + ". Your participation has been removed and you have been set as invited. If you want to change your calendar schedule or to get further information you can log with your profile.\n\nThe meteocal staff";
        
        //sending an e-mail to the recipient
        sendEmail(receiver.getEmail(), emailMessage, object);
    }
    
    
}
